package com.liujit.standard.basis.generator.controller;

import com.liujit.standard.basis.GeneratorApplication;
import com.liujit.standard.basis.generator.util.ToolUtil;
import com.liujit.standard.basis.generator.action.config.WebGeneratorConfig;
import com.liujit.standard.basis.generator.action.model.GenQo;
import com.liujit.standard.basis.generator.action.model.Table;
import com.liujit.standard.basis.generator.action.model.Template;
import com.liujit.standard.basis.generator.service.GeneratorService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Description 代码生成接口
 * @Author LiuJun
 * @Date 2020/8/14 10:39 上午
 */
@RestController
@RequestMapping("/generator/code")
public class CodeController {

    @Value("${spring.datasource.driver-class-name}")
    private String driverName;

    @Value("${spring.datasource.url}")
    private String url;

    @Value("${spring.datasource.userName}")
    private String userName;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${project.module}")
    private String projectModule;

    @Value("${package.name}")
    private String packageName;

    /**
     * 获取数据库表信息
     *
     * @return
     */
    @GetMapping(value = "/getTable")
    public List<Table> getTable() {
        GeneratorService generatorService = new GeneratorService();
        generatorService.setDataSourceConfig(driverName, userName, password, url);
        String schema = url.substring(url.indexOf(":3306") + 6, url.indexOf("?"));
        return generatorService.getTable(schema);
    }

    /**
     * 获取模板信息
     *
     * @return
     */
    @GetMapping(value = "/getTemplate")
    public List<Template> getTemplate() {
        GeneratorService generatorService = new GeneratorService();
        return generatorService.getTemplate();
    }

    /**
     * 获取默认信息
     *
     * @return
     */
    @GetMapping(value = "/getGen")
    public GenQo getGen() {
        GenQo genQo = new GenQo();
        String path = ToolUtil.getWebRootPath(null);
        genQo.setProjectPath(path.replace("bamboo-generator", projectModule));
        genQo.setAuthor(System.getenv("USER"));
        genQo.setPackageName(GeneratorApplication.class.getPackage().getName() + "." + packageName);
        return genQo;
    }

    /**
     * 生成代码
     *
     * @return
     */
    @PostMapping(value = "/generate")
    public void generate(@RequestBody GenQo genQo) {
        genQo.setDriverName(driverName);
        genQo.setUrl(url);
        genQo.setUserName(userName);
        genQo.setPassword(password);
        WebGeneratorConfig webGeneratorConfig = new WebGeneratorConfig(genQo);
        webGeneratorConfig.doGeneration();
    }
}
